<template>
  <div id="Stu">
    <el-breadcrumb
      separator="/"
      style="padding-left: 10px; padding-bottom: 10px; font-size: 12px"
    >
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>学生管理</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card" shadow="hover">
      <el-form
        :inline="true"
        :model="queryMap"
        size="small"
        class="demo-form-inline"
      >
        <el-form-item label="学生姓名">
          <el-input v-model="queryMap.stuName" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="学号">
          <el-input v-model="queryMap.stuNum" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="班级">
          <el-select
            clearable
            v-model="queryMap.classId"
            filterable
            remote
            reserve-keyword
            placeholder="请输入班级"
            :remote-method="getClassByKey"
            :loading="loading"
          >
            <el-option
              v-for="item in classList"
              :key="item.classId"
              :label="item.className"
              :value="item.classId"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            @click="search"
            type="primary"
            icon="el-icon-search"
            :loading="loading"
            round
            >查询</el-button
          >
          <el-button
            @click="(show = true), (currentUser = {})"
            type="info"
            icon="el-icon-plus"
            round
            >新增</el-button
          >
        </el-form-item>
        <el-form-item
          ><download-excel
            :fields="json_data"
            :data="example"
            worksheet="sheet1"
            name="学生信息模板.xls"
          >
            <el-tooltip
              class="item"
              effect="dark"
              content="学生信息模板"
              placement="top-start"
              ><el-button type="success" icon="el-icon-download" round
                >模板导出</el-button
              ></el-tooltip
            ></download-excel
          ></el-form-item
        >
        <el-form-item>
          <!--limit:最大上传数，on-exceed：超过最大上传数量时的操作  -->
          <el-upload
            class="upload-demo"
            icon="el-icon-upload2"
            action=""
            :on-change="handleChange"
            :on-remove="handleRemove"
            :on-exceed="handleExceed"
            :limit="limitUpload"
            accept="application/vnd.openxmlformats-    
        officedocument.spreadsheetml.sheet,application/vnd.ms-excel"
            :auto-upload="false"
          >
            <el-tooltip
              class="item"
              effect="dark"
              content="学生信息导入入口"
              placement="top-start"
            >
              <el-button
                size="small"
                type="warning"
                round
                icon="el-icon-upload2"
                >学生信息导入</el-button
              >
            </el-tooltip>
          </el-upload>
        </el-form-item>
      </el-form>
      <template>
        <el-table
          :data="stuList"
          border
          stripe
          size="mini"
          style="width: 100%; margin-top: 5px"
        >
          <el-table-column
            prop="num"
            label="学号"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="username"
            label="姓名"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="className"
            label="班级"
            align="center"
          ></el-table-column>
          <el-table-column label="当前用户是否可用" width="200" align="center">
            <template slot-scope="scope">
              <el-switch v-model="scope.row.status" disabled></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" align="center">
            <template slot-scope="scope">
              <el-button
                type="text"
                icon="el-icon-view"
                size="mini"
                :loading="loading"
                @click="getScore(scope.row.userId)"
                >学分</el-button
              >
              <el-button
                type="text"
                icon="el-icon-edit"
                size="mini"
                :loading="loading"
                @click="getCurrentUser(scope.row.userId)"
                >编辑</el-button
              >
              <el-button
                type="text"
                icon="el-icon-delete"
                size="mini"
                :loading="loading"
                @click="delCurrentStuByStuId(scope.row.userId)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </template>
      <!-- 分页 -->
      <el-pagination
        style="margin-top: 10px"
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="this.queryMap.page"
        :page-sizes="[10, 50, 100]"
        :page-size="this.queryMap.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>
    <el-dialog title="学生详情信息" :visible.sync="show" width="400px">
      <el-form :model="currentUser" align="center">
        <el-form-item label="学号" label-width="70px">
          <el-input
            v-model="currentUser.num"
            autocomplete="off"
            style="width: 220px"
          ></el-input>
        </el-form-item>
        <el-form-item label="用户名" label-width="70px">
          <el-input
            v-model="currentUser.username"
            autocomplete="off"
            style="width: 220px"
          ></el-input>
        </el-form-item>
        <el-form-item label="密码" label-width="70px">
          <el-input
            v-model="currentUser.password"
            showPassword
            autocomplete="off"
            style="width: 220px"
          ></el-input>
        </el-form-item>
        <el-form-item label="班级" label-width="70px">
          <el-select
            v-model="currentUser.classId"
            filterable
            remote
            reserve-keyword
            placeholder="请输入班级"
            :remote-method="getClassByKey"
            :loading="loading"
          >
            <el-option
              v-for="item in classList"
              :key="item.classId"
              :label="item.className"
              :value="item.classId"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="学生类型" label-width="70px">
          <el-select v-model="currentUser.userType" placeholder="请选择">
            <el-option :key="1" label="本科" :value="1"></el-option>
            <el-option :key="2" label="专升本" :value="2"></el-option>
            <el-option :key="3" label="专科" :value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否可用" label-width="70px">
          <el-select v-model="currentUser.status" placeholder="请选择">
            <el-option :key="true" label="可用" :value="true"></el-option>
            <el-option :key="false" label="不可用" :value="false"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          :loading="loading"
          @click="updateCurrentUser(currentUser.userId)"
          >确 定</el-button
        >
        <el-button @click="show = false">取 消</el-button>
      </div>
    </el-dialog>
    <el-drawer title="当前学生学分详情" :visible.sync="drawer" direction="rtl">
      <el-tree :data="scoreList" accordion>
        <span class="custom-tree-node" slot-scope="{ node, data }">
          <span :title="data.topicTypeName" style="margin-top: 5px">{{
            data.topicTypeName
          }}</span>
          <span style="margin-top: 5px">
            <a class="my-badge" :title="data.totalScore">{{
              data.totalScore | numberFormat
            }}</a>
          </span>
        </span>
      </el-tree>
    </el-drawer>
  </div>
</template>
<style scoped>
.my-badge {
  color: #fff;
  background: #99a9bf;
  padding: 3px 8px;
  font-size: 12px;
  line-height: 12px;
  border-radius: 20px;
  text-align: center;
}
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
</style>
<script>
import { mapState } from "vuex";
import {
  queryStuByPage,
  queryClassesByClassName,
  queryCurrentUser,
  editCurrentUser,
  saveCurrentUser,
  importStuList2Excels,
  delCurrentStu,
  queryCurrentTopicTypeScore,
} from "api/api";
export default {
  data() {
    return {
      queryMap: { page: 1, size: 10 },
      loading: false,
      show: false,
      stuList: [],
      classList: [],
      total: 0,
      currentUser: {},
      json_data: {
        学号: "num",
        姓名: "username",
        密码: "password",
        "学生类型(1 本科/2 专升本/3 专科)": "userType",
        "班级(必须与系统中的信息保持一致)": "className",
        "是否可用(必须填1或0)": "disabled",
      },
      example: [
        {
          num: "20180210113",
          username: "尧国庆",
          password: "123456",
          userType: 2,
          className: "18软件工程2班",
          disabled: 1,
        },
      ],
      limitUpload: 2,
      excelStuList: [],
      scoreList: [],
      drawer: false,
    };
  },
  computed: {
    ...mapState(["userInfo"]),
  },
  methods: {
    //改变页码
    handleSizeChange(newSize) {
      this.queryMap.size = newSize;
      this.getStuByPage();
    },
    //翻页
    handleCurrentChange(current) {
      this.queryMap.page = current;
      this.getStuByPage();
    },
    //获取学生信息
    async getStuByPage() {
      await queryStuByPage(this.userInfo.sessionId, this.queryMap).then(
        (res) => {
          if (!res.flag) {
            this.$message.error(res.message);
          } else {
            this.total = res.data.total;
            this.stuList = res.data.rows;
          }
        }
      );
    },
    //获取班级信息
    async getClassByKey(query) {
      if (query != null) {
        queryClassesByClassName(this.userInfo.sessionId, query).then((res) => {
          if (!res.flag) {
            this.$message.error(res.message);
          } else {
            this.classList = res.data;
          }
        });
      }
    },
    search() {
      //进行初始化操作
      this.total = 0;
      this.stuList = [];
      queryStuByPage(this.userInfo.sessionId, this.queryMap).then((res) => {
        if (!res.flag) {
          this.$message.error(res.message);
        } else {
          this.total = res.data.total;
          this.stuList = res.data.rows;
        }
      });
    },
    //获取当前用户详情信息
    async getCurrentUser(userId) {
      //初始化操作
      this.currentUser = {};
      this.show = true;
      this.loading = true;
      await queryCurrentUser(this.userInfo.sessionId, userId).then((res) => {
        if (!res.flag) {
          this.$message.error(res.message);
          this.loading = false;
        } else {
          this.loading = false;
          this.currentUser = res.data;
        }
      });
    },
    //获取班级信息
    async getClassByKey(query) {
      //初始化操作
      this.classList = [];
      await queryClassesByClassName(this.userInfo.sessionId, query).then(
        (res) => {
          if (!res.flag) {
            this.$message.error(res.message);
          } else {
            this.classList = res.data;
          }
        }
      );
    },
    //更新当前用户信息
    async updateCurrentUser(userId) {
      this.loading = true;
      this.currentUser.type = true;
      if (userId != null) {
        //更新操作
        await editCurrentUser(this.userInfo.sessionId, this.currentUser).then(
          (res) => {
            if (!res.flag) {
              this.loading = false;
              this.$message.error(res.message);
              this.loading = false;
            } else {
              this.$message({
                type: "success",
                message: "更新成功！",
              });
              this.loading = false;
              this.show = false;
              this.getStuByPage();
            }
          }
        );
      } else {
        this.currentUser.type = true;
        //新增操作
        await saveCurrentUser(this.userInfo.sessionId, this.currentUser).then(
          (res) => {
            if (!res.flag) {
              this.loading = false;
              this.$message.error(res.message);
            } else {
              this.$message({
                type: "success",
                message: "新增成功！",
              });
              this.loading = false;
              this.show = false;
              this.getStuByPage();
            }
          }
        );
      }
    },
    //上传文件时处理方法
    async handleChange(file, fileList) {
      this.fileTemp = file.raw;
      if (this.fileTemp) {
        if (
          this.fileTemp.type ==
            "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ||
          this.fileTemp.type == "application/vnd.ms-excel"
        ) {
          await this.importStuList(this.fileTemp);
        } else {
          this.$message({
            type: "warning",
            message: "附件格式错误，请删除后重新上传！",
          });
        }
      } else {
        this.$message({
          type: "warning",
          message: "请上传附件！",
        });
      }
    },
    //超出最大上传文件数量时的处理方法
    async handleExceed() {
      this.$message({
        type: "warning",
        message: "超出最大上传文件数量的限制！",
      });
      return;
    },
    //移除文件的操作方法
    async handleRemove(file, fileList) {
      this.fileTemp = null;
    },
    //数据清洗
    async importStuList(obj) {
      let _this = this;
      let inputDOM = this.$refs.inputer;
      // 通过DOM取文件数据
      this.file = event.currentTarget.files[0];
      var rABS = false; //是否将文件读取为二进制字符串
      var f = this.file;
      var reader = new FileReader();
      //if (!FileReader.prototype.readAsBinaryString) {
      FileReader.prototype.readAsBinaryString = function (f) {
        var binary = "";
        var rABS = false; //是否将文件读取为二进制字符串
        var pt = this;
        var wb; //读取完成的数据
        var outdata;
        var reader = new FileReader();
        reader.onload = (e) => {
          var bytes = new Uint8Array(reader.result);
          var length = bytes.byteLength;
          for (var i = 0; i < length; i++) {
            binary += String.fromCharCode(bytes[i]);
          }
          //此处引入，用于解析excel
          var XLSX = require("xlsx");
          if (rABS) {
            wb = XLSX.read(btoa(fixdata(binary)), {
              //手动转化
              type: "base64",
            });
          } else {
            wb = XLSX.read(binary, {
              type: "binary",
            });
          }
          outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]);
          //outdata就是读取的数据（不包含标题行即表头，表头会作为对象的下标）
          //此处可对数据进行处理
          let arr = [];
          outdata.map((v) => {
            let obj = {};
            obj.num = v["学号"];
            obj.username = v["姓名"];
            obj.password = v["密码"];
            obj.userType = v["学生类型(1 本科/2 专升本/3 专科)"];
            obj.className = v["班级(必须与实例保持一致)"];
            obj.status = v["是否可用(必须填1或0)"];
            arr.push(obj);
          });
          _this.importData(arr);
        };
        reader.readAsArrayBuffer(f);
      };
      if (rABS) {
        reader.readAsArrayBuffer(f);
      } else {
        reader.readAsBinaryString(f);
      }
    },
    //数据导入
    importData(data) {
      console.log(data);
      this.loading = true;
      importStuList2Excels(this.userInfo.sessionId, data).then((res) => {
        if (!res.flag) {
          this.$message.error(res.message + ":" + res.data);
          this.loading = false;
        } else {
          this.$message({
            type: "success",
            message: "数据导入成功！",
          });
          this.getStuByPage();
          this.loading = false;
        }
      });
    },
    //根据学生Id删除对应的学生信息
    async delCurrentStuByStuId(stuId) {
      this.loading = true;
      var res = await this.$confirm(
        "此操作将永久删除该学生数据，是否继续!",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch(() => {
        this.$message({
          type: "info",
          message: "已取消操作！",
        });
        this.loading = false;
      });
      if (res == "confirm") {
        delCurrentStu(stuId)
          .then((res) => {
            if (!res.flag) {
              this.$message.error(res.message);
              this.loading = true;
            } else {
              this.$message({
                type: "success",
                message: "删除成功！",
              });
              this.loading = false;
              this.getStuByPage();
            }
          })
          .catch(() => {
            this.loading = false;
          });
      }
    },
    getScore(stuId) {
      queryCurrentTopicTypeScore(stuId).then((res) => {
        if (!res.flag) {
          this.$message.error(res.message);
        } else {
          this.drawer = true;
          this.scoreList = res.data;
        }
      });
    },
  },
  mounted() {
    this.getStuByPage();
    this.getClassByKey();
  },
};
</script>